package cn.xianyang.basic.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

public class MailSenderUtils implements ApplicationContextAware {
    public static ApplicationContext context;

    /** 获取工厂 */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    /**
     * 简单发送
     * @param to 发送地址
     * @param message 邮件内容
     */
    public static void simpleSend(String to,String title,String message){
        //通过上下文对象根据bean id获取bean对象  JavaMailSender的beanid是mailSender
        JavaMailSender javaMailSender = (JavaMailSender)context.getBean("mailSender");
        SimpleMailMessage simpleMessage = new SimpleMailMessage();
        simpleMessage.setFrom("806779279@qq.com");
        simpleMessage.setTo(to);
        simpleMessage.setSubject(title);
        simpleMessage.setText(message);
        javaMailSender.send(simpleMessage);
    }

    /**
     * 复杂邮件工具类
     * @param to
     * @param title
     * @param message
     */
    public static void mimeSend(String to,String title,String message){
        //通过上下文对象根据bean id获取bean对象  JavaMailSender的beanid是mailSender
        JavaMailSender javaMailSender = (JavaMailSender)context.getBean("mailSender");
        try {
            //创建复杂邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //发送复杂邮件的工具类
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("806779279@qq.com");
            helper.setSubject(title);
            //第二个参数 true 代表是否是一个html内容
            helper.setText(message,true);
            /*
            "<h1>新型冠状病毒防护守则</h1><h3>h3标签</h3>"+
            "<img src='http://123.207.27.208/group1/M00/00/08/CgAIC2Kmz-OAJpZcAAB9hyRh4uY958.jpg\"' />"
            * */
            //添加附件 写死的...
            /*helper.addAttachment("文件名.jpg",new File("C:\\aa.jpg"));
            helper.addAttachment("压缩文件", new File("C:\\resources.zip"));*/
            //收件人
            helper.setTo(to);
            //发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }


    }


}
